<template>
    <div class="container">
        <!--查询部分-->
        <!--inline=true水平摆放form表单-->
        <el-form ref="roleQueryForm" :inline="true" :model="roleQueryForm">

            <el-form-item prop="name" size="small" label="角色名称">
                <el-input clearable v-model="roleQueryForm.name" @keydown.enter.native="searchRole" placeholder="请输入菜单名称"></el-input>
            </el-form-item>

            <el-form-item prop="status" size="small" label="角色状态">
                <el-select @change="searchRole" clearable v-model="roleQueryForm.status" placeholder="菜单状态">
                    <el-option :key="index" v-for="(item,index) in $dictMap('status')" :label="item.desc" :value="item.value"></el-option>
                    <!--<el-option label="禁用" value=0></el-option>-->
                </el-select>
            </el-form-item>

            <el-form-item size="mini">
                <el-button @click="searchRole" style="width: 80px" :disabled="authenticate('查询')" type="primary">
                    <i class="iconfont icon-search-line"/><span>查询</span>
                </el-button>
            </el-form-item>

            <el-form-item size="mini">
                <el-button @click="$refs.roleQueryForm.resetFields()" style="width: 80px" type="normal"><i
                        class="iconfont icon-zhongzhi-"/><span>重置</span>
                </el-button>
            </el-form-item>

            <el-form-item size="mini">
                <el-button plain style="width: 80px"
                           :disabled="authenticate('新增')"
                           type="primary" @click="addRole"><i
                        class="iconfont icon-jia"/><span>新增</span></el-button>
            </el-form-item>
        </el-form>
        <!--查询部分-->


        <!--菜单列表 列表部分-->
        <el-table
            :header-cell-style="{'text-align':'center',background:'#f8f8f9',color:'#606266'}"
            :cell-style="{'text-align':'center'}"
            :data="roleDatas"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            border
            default-expand-all>
            <el-table-column
                prop="name"
                label="角色名称">
            </el-table-column>

            <el-table-column
                prop="code"
                label="权限字符">
            </el-table-column>

            <el-table-column
                prop="sort"
                sortable
                label="排序">
            </el-table-column>

            <el-table-column
                width="200"
                label="状态">
                <template slot-scope="scope">
                    <el-switch
                            :disabled="authenticate('状态')"
                        v-model="scope.row.status"
                        @change="statusChange(scope.row)"
                        :active-value="'1'"
                        :inactive-value="'0'"
                        active-color="#13ce66"
                        inactive-color="#a9acb8"
                        active-text="开启"
                        inactive-text="禁用">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column
                prop="createTime"
                sortable
                label="创建时间">
            </el-table-column>

            <el-table-column
                prop="updateTime"
                sortable
                label="更新时间">
            </el-table-column>

            <el-table-column
                label="操作">
                <template slot-scope="scope">
                    <el-button :disabled="authenticate('编辑')"
                                size="mini" type="primary"
                               @click="editRole(scope.row)" round>编辑
                    </el-button>
                    <el-button
                            :disabled="authenticate('删除')"
                            size="mini" type="danger" @click="delRole(scope.row,scope.$index)" round>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--菜单列表 列表部分-->


        <!--添加菜单 dialog-->
        <el-dialog @close="closeDialog" :title="dialogName" :visible.sync="addRoleVisible">
            <!--label-width 表单里面label的标签-->
            <el-form ref="roleAddForm" :rules="roleRules" :model="roleForm" label-width="80px">

                <el-form-item prop="name" label="角色名称">
                    <el-input v-model="roleForm.name"></el-input>
                </el-form-item>

                <el-form-item prop="code" label="权限字符">
                    <el-input v-model="roleForm.code"></el-input>
                </el-form-item>

                <el-form-item prop="sort" label="显示排序">
                    <el-input-number v-model="roleForm.sort" controls-position="right" :min="1"
                                     :max="15"></el-input-number>
                </el-form-item>

                <!--编辑状态无需显示该行-->
                <el-form-item v-if="!roleForm.id" label="菜单状态">
                    <el-radio :key="index" v-for="(item,index) in $dictMap('status')" v-model="roleForm.status" :label="item.value">
                        {{item.desc}}</el-radio>
                </el-form-item>

                <el-form-item label="权限菜单">
                    <!--这里是引用的第三方组件-->
                    <el-select-tree
                            :check-strictly="false"
                            :clearable= "true"
                            :multiple = "true"
                            style="width:100%"
                            placeholder="菜单"
                            :props="{ value: 'id', label: 'name', children: 'childMenu'}"
                            :data="menuTree"
                            v-model="roleForm.menuIds"
                    ></el-select-tree>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="oprRole">确 定</el-button>
            </div>
        </el-dialog>
        <!--添加菜单 dialog-->

        <!-- 分页组件 -->
        <!--@size-change="handleSizeChange"-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        <!-- 分页组件 -->

    </div>
</template>

<script>
    import {showLoading,hideLoading} from "@/util/loadingUtil";

    export default {
        name: "Role",
        inject: ["mainReload"],
        data() {
            return {
                authenticate(name) {
                    return this.$authenticate(this.$route.path,name)
                },

                roleDatas:[],
                roleQueryForm: {status:null,name:''},
                dialogName: '',
                addRoleVisible: false,
                roleForm: {},
                roleRules:{
                    name:[
                        { required: true, message: '请输入角色名称',trigger: 'blur' }
                    ],
                    sort:[
                        { required: true, message: '请选择角色排序',trigger: 'blur' }
                    ],
                    code:[
                        { required: true, message: '请选择权限编码',trigger: 'blur' }
                    ]
                },

                // 菜单数据
                menuTree:[],

                //分页参数
                total:0,
                pageNum:1,
                pageSize:10
            }
        },
        created() {
            this.$axiosApi.getRoles(this.roleQueryForm,(list,total)=>{
                this.roleDatas = list
                this.total = total
            })

            this.$axiosApi.getMenuTree({status:1},(data)=>{
                this.menuTree = data
            })
        },

        //computed:{
        //    ...mapState({
        //        menuTree:"allMenuTree"
        //    }),
        //},

        methods: {
            init() {
                this.roleForm = {
                    status:this.$dictMapDefault('status'),
                    menuIds:[]
                }
            },

            closeDialog() {
                this.init()
                this.addRoleVisible = false;
                this.$nextTick(() => {
                    this.$refs['roleAddForm'].clearValidate()
                })
            },

            //分页插件，当前页修改时触发
            handleCurrentChange(pageNum) {
                this.roleQueryForm.pageNum = pageNum
                this.roleQueryForm.pageSize = this.pageSize
                this.$axiosApi.getRoles(this.roleQueryForm, (list) => {
                    this.roleDatas = list
                    this.pageNum = pageNum
                })
            },

            //分页插件，条数修改时触发
            handleSizeChange(pageSize) {
                this.pageNum = 1;
                this.roleQueryForm.pageNum = 1
                this.roleQueryForm.pageSize = pageSize
                this.$axiosApi.getRoles(this.roleQueryForm, (data, total) => {
                    this.roleDatas = data
                    this.total = total
                    this.pageSize = pageSize
                })
            },

            //控制状态的开关按钮触发
            statusChange(role) {
                this.$put("/role/editRole", role).then(() => {
                    if (role.status === '1') {
                        this.$message({
                            message: "已开启",
                            type: 'success'
                        });
                    } else {
                        this.$message("已禁用")
                    }
                })
            },

            //查询模块，搜索按钮
            searchRole() {
                //点击搜索后，要重置pageNum和pageSize，以免被之前的分页参数影响
                this.pageNum = 1
                this.pageSize = 10
                this.roleQueryForm.pageNum = 1;
                this.roleQueryForm.pageSize = 10;
                this.$axiosApi.getRoles(this.roleQueryForm, (list, total) => {
                    this.roleDatas = list
                    this.total = total
                })
            },

            delRole(role,index) {
                this.$confirm(`确定永久删除 '${role.name}' 角色吗？`, '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.$del("/role/delRole", {
                        id: role.id
                    }).then(() => {
                        this.$message("删除成功");
                        this.mainReload();

                        //如果当前页只剩下一条数据的话，就刷新路由，否则删除roleDatas即可
                        //if (this.roleDatas.length <= 1) {
                        //    this.mainReload();
                        //} else {
                        //    this.roleDatas.splice(index,1)
                        //}
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: "已取消删除"
                    });
                });

            },

            addRole() {
                this.addRoleVisible=true;
                this.dialogName='添加角色'
                this.init()
            },

            //点击编辑按钮触发
            editRole(roleForm) {
                this.$get("/role/getRoleMenuIds",{
                    id:roleForm.id
                }).then(({data})=>{
                    this.addRoleVisible = true;
                    this.roleForm = JSON.parse(JSON.stringify(roleForm));
                    this.roleForm.menuIds = data
                    this.dialogName = '编辑角色'
                })

            },

            // 添加/编辑框 点击确认的时候
            oprRole() {
                //form表单规则校验
                this.$refs['roleAddForm'].validate(async (valid) => {
                    if (!valid) {
                        return false
                    }

                    // 该方法用来处理新增还是处理编辑，关键在于查看this.roleForm对象是否具有id，有就是编辑，无这是新增
                    showLoading();

                    // 关闭编辑框
                    this.addRoleVisible = false

                    if (!this.roleForm.id) {
                        await this.$post("/role/addRole", this.roleForm)
                    } else {
                        await this.$put("/role/editRole", this.roleForm)
                    }


                    hideLoading()

                    // 提示框
                    this.$message({
                        message: "操作成功",
                        type: "success",
                    })

                    // 因为编辑的时候可能已经添加了id，记得要清除id
                    this.roleForm = {id: null}

                    //重新装载数据 todo key值写成枚举
                    this.mainReload();

                });
            },
        }
    }
</script>

<style scoped>

</style>